package com.platform.common.utils.pay;

import java.io.ByteArrayInputStream;
import java.security.PrivateKey;
import java.security.Signature;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;

/***
 * 签名助手
 */
public class SignUtil {
    /**
     * SHA256withRSA签名
     * @author xpl
     * @param content
     * @param privateKey
     * @param charset
     * @return
     */
    public static String signBySHA256WithRSA(String content, String privateKey, String charset){
        if(StringUtils.isBlank(privateKey)){
            //缺少签名私钥
            return null;
        }
        try {
            PrivateKey priKey = PemUtil
                    .loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes(charset)));

            Signature signature = Signature.getInstance("SHA256withRSA");
            signature.initSign(priKey);
            signature.update(content.getBytes(charset));

            return org.apache.commons.codec.binary.Base64.encodeBase64String(signature.sign());
        } catch (Exception e) {
            //签名失败
            return null;
        }
    }
}
